package cn.livingCloud.service.impl;

import cn.livingCloud.dto.ReportRuleFormDto;
import cn.livingCloud.dto.ReportRuleListDto;
import cn.livingCloud.entity.core.PushGroup;
import cn.livingCloud.entity.core.ReportRule;
import cn.livingCloud.repository.PushGroupMapper;
import cn.livingCloud.repository.ReportRuleMapper;
import cn.livingCloud.service.ReportRuleService;
import cn.livingCloud.service.impl.operation.PreviewDateLoader;
import cn.livingCloud.service.impl.operation.ReportRuleFormDtoLoader;
import com.alibaba.druid.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * Created by DingJie on 2016/6/27.
 */
@Service
public class ReportRuleServiceImpl implements ReportRuleService {
    @Autowired
    private ReportRuleMapper mapper;
    @Autowired
    private PushGroupMapper pushGroupMapper;

    @Override
    public void loadReportRuleListDto(ReportRuleListDto listDto) {
        listDto.addAllList(mapper.getList(listDto));
    }

    @Override
    public void edit(ReportRuleFormDto formDto) {
        if (StringUtils.isEmpty(formDto.getUuid())) {
            ReportRule reportRule = new ReportRule();
            reportRule.setContent(formDto.getContent());
            reportRule.setSql(formDto.getSql());
            reportRule.setName(formDto.getName());
            reportRule.setDeptUuid(formDto.getDeptUuid());
            mapper.insert(reportRule);
        } else {
            ReportRule reportRule = mapper.selectByPrimaryKey(formDto.getUuid());
            reportRule.setContent(formDto.getContent());
            reportRule.setSql(formDto.getSql());
            reportRule.setDeptUuid(formDto.getDeptUuid());
            reportRule.setName(formDto.getName());
            mapper.updateByPrimaryKey(reportRule);
        }
    }

    @Override
    public void delete(String uuid) {
        ReportRule reportRule = mapper.selectByPrimaryKey(uuid);
        reportRule.setArchive(true);
        mapper.updateByPrimaryKey(reportRule);
        //删除报表规则的情况下,推送分组设置为禁用
        List<PushGroup> lists = pushGroupMapper.getPushGroupByReportRuleUuid(uuid);
        for (PushGroup pushGroup : lists) {
            pushGroup.setState(true);
            pushGroupMapper.updateByPrimaryKey(pushGroup);
        }
    }

    @Override
    public void loadReportRuleFormDto(ReportRuleFormDto formDto) {
        ReportRuleFormDtoLoader formDtoLoader = new ReportRuleFormDtoLoader(formDto);
        formDtoLoader.loadFormDto();
    }

    @Override
    public String loadsPreviewDate(String uuid, HttpServletRequest request) {
        PreviewDateLoader loader = new PreviewDateLoader(uuid, request);
        return loader.loader();
    }

    @Override
    public String loadContent(String uuid) {
        return mapper.selectByPrimaryKey(uuid).getContent();
    }
}
